//
//  CoGeThreadSafeMutableArray.m
//  CoGe
//
//  Created by Tamas Nagy on 4/30/11.
//  Copyright 2011 home. All rights reserved.
//

#import "CoGeThreadSafeMutableArray.h"


@implementation CoGeThreadSafeMutableArray

- (id) init;
{
    self = [super init];
    if (self != nil) {
        lock = [[NSLock alloc] init];
        theArray = [[NSMutableArray alloc] init]; 
    }
    
    return self;
}

-(id)initWithCapacity:(NSUInteger)numItems
{
    self = [self init];
    if (self != nil) {
        [theArray release];
        theArray = [[NSMutableArray alloc] initWithCapacity: numItems];
    }
    
    return self;
}



- (NSUInteger) count;
{
    [lock lock];
    NSUInteger _temp = [theArray count];
    [lock unlock];
    return _temp;
}

- (NSEnumerator *)objectEnumerator
{
    NSEnumerator    *result;
    
    [lock lock];
    result = [theArray objectEnumerator];
    [lock unlock];
    
    return result;
}

- (NSEnumerator *)reverseObjectEnumerator
{
    NSEnumerator    *result;
    
    [lock lock];
    result = [theArray reverseObjectEnumerator];
    [lock unlock];
    
    return result;
}


- (id)objectAtIndex:(NSUInteger)index
{
    id    result;
    
    [lock lock];
    result = [theArray objectAtIndex:index];
    [[result retain] autorelease];
    [lock unlock];
    
    return result;
}

- (void)replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject {

    [[anObject retain] autorelease];
    
    [lock lock];
    [theArray replaceObjectAtIndex:index withObject:anObject];
    [lock unlock];

}

- (void)removeAllObjects {
    [lock lock];
    [theArray removeAllObjects];
    [lock unlock];

}

- (void)removeLastObject {

    [lock lock];
    [theArray removeLastObject];
    [lock unlock];

}

- (void)addObject:(id)anObject
{
    [[anObject retain] autorelease];
    
    [lock lock];
    [theArray addObject:anObject];
    [lock unlock];
}


- (void)removeObjectAtIndex:(NSUInteger)index
{
    [lock lock];
    [theArray removeObjectAtIndex:index];
    [lock unlock];
}

- (void)insertObject:(id)anObject atIndex:(NSUInteger)index
{
    [[anObject retain] autorelease];
    
    [lock lock];
    [theArray insertObject:anObject atIndex:index];
    [lock unlock];
}

- (void) dealloc;
{
    [lock tryLock];
    [lock unlock];
    [theArray release];
    [lock release];
    
    [super dealloc];
}

@end
